using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using IGlobalist.Cms.Common;
using IGlobalist.Cms.Bll;
using IGlobalist.Cms.Model;
using System.Collections.Generic;

namespace IGlobalist.Cms.Admin.Control
{
    public partial class UserAddEdit : AdminBaseUserControl
    {
        public event EventHandler SaveUser;
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public void DoNew(object sender, EventArgs e)
        {
            
            ViewState["User"] = null;
            tbName.Focus();
            ddlClassPage.DataBind();                        
            ddlClassPage.Enabled = true;
            ddlClassPage.SelectedIndex = 0;            
            lblStatus.Text = "Add New User";
            ViewState["Roles"] = null;
            tbDescription.Text = "";
            tbEmail.Text = "";
            tbPassword.Text ="";
            tbFirstName.Text = "";
            tbLastName.Text = "";
            tbMiddle.Text = "";
            tbName.Text = "";
            lblErrorRole.Text = "";
            tbName.Enabled = true;            
            BindRoles();
            ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClassPage.SelectedValue));
            if (clazz != null)
            {
                ucCmsExtPropertiesForm.PropertyList = clazz.PropertyList;            
            }
            if (ucCmsExtPropertiesForm.PropertyList.Count > 13)
                fsExt.Visible = true;
            else fsExt.Visible = false;
        }

        public void DoSave(object sender, EventArgs e)
        {
            string  roles ="";
            lblErrorRole.Text = "";
            bool success = false;
            IUser user = new User();
            if (ViewState["User"] != null)
            {
                user = (IUser)ViewState["User"];
                //user.EditedBy = ExpMembership.GetUser().ID;
            }
            //else
            //{
            //    //user.Author = ExpMembership.GetUser().ID;
            //}
            user.Class = ClassController.GetClass(Convert.ToInt64(ddlClassPage.SelectedValue));
            user.ClassTypeID = Convert.ToInt16(CmsObjectType.User);
            user.ClassID = Convert.ToInt64(ddlClassPage.SelectedValue);
            Session[SessionVariable.Clazz.CurrentID] = Convert.ToInt64(ddlClassPage.SelectedValue);
            user.ExtPropertyList = ucCmsExtPropertiesForm.PropertyList;
            user.Description = tbDescription.Text;
            user.Name = tbName.Text;
            user.Email = tbEmail.Text;
            user.Firstname = tbFirstName.Text;
            user.Lastname = tbLastName.Text;
            user.Middle = tbMiddle.Text;
            user.Password = tbPassword.Text;            
            //get role
                for (int i=0;i<dlRoles.Items.Count;i++)
                {
                    Repeater rptRole= (Repeater) dlRoles.Items[i].FindControl("rptRole");
                    for(int j=0;j<rptRole.Items.Count;j++)
                    {
                        CheckBox cbRole = (CheckBox) rptRole.Items[j].FindControl("cbRole");
                        if (cbRole.Checked==true)
                            roles = String.Format("{0},{1}", roles,((HiddenField)rptRole.Items[j].FindControl("hdnRoleID")).Value);

                    }
                }
                String status = "Create User";
                if (roles.Length > 0)
                {
                    roles = roles.Substring(1, roles.Length - 1);
                    String[] sRole = roles.Split(',');
                    user.Roles = sRole;                    
                    if (ViewState["User"] != null)
                    {
                        UserController.UpdateUser(user);
                        success = true;
                        status = "Update Successful";
                    }
                    else
                    {
                        if (IsExist(user.Name))
                        {
                            UserController.InsertUser(user);
                            lblError.Text = "";
                            success = true;
                            lblStatus.Text = "Insert Successful";
                        }
                        else
                            lblError.Text = "Name is exist";
                    }

                    if ((SaveUser != null) && (success == true))
                    {
                        SaveUser(this, new EventArgs());
                        ddlClassPage.Enabled = false;
                    }
                    
                }
                if(roles.Length ==0) lblErrorRole.Text = "Require choice at least one role";
                lblStatus.Text = status;
                lblStatus.Visible = true;
        }

        public void DoCopy(object sender, EventArgs e)
        {
            ViewState["User"] = null;
            tbName.Text = "";
        }

        public void DoEditPage(object sender, EventArgs e)
        {
            ddlClassPage.DataBind();            
            ddlClassPage.Enabled = false;            
            ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClassPage.SelectedValue));
            lblErrorRole.Text = "";
            lblStatus.Text = "Edit User";
            UserList ul = (UserList)sender;
            long userID = Convert.ToInt64(ul.SelectedID);
            IUser user = UserController.GetUser(userID);
            ViewState["User"] = user;
            tbName.Text = user.Name;
            tbFirstName.Text = user.Firstname;
            tbLastName.Text = user.Lastname;
            tbMiddle.Text = user.Middle;
            tbName.Enabled = false;
            tbDescription.Text = user.Description;
            tbEmail.Text = user.Email;
            tbPassword.Text = user.Password;
            ddlClassPage.SelectedValue = user.ClassID.ToString();
            //bind role
            ViewState["Roles"] = user.Roles;
            BindRoles();
            if (ucCmsExtPropertiesForm.PropertyList.Count > 13)
                fsExt.Visible = true;
            else fsExt.Visible = false;
            ucCmsExtPropertiesForm.PropertyList = user.ExtPropertyList;
            
        }

        private void BindRoles()
        {
            IList<ICmsClass> clazzList = ClassController.GetClassListByClassTypeID(Convert.ToInt16(CmsObjectType.Role));
            dlRoles.DataSource = clazzList;
            dlRoles.DataBind();
        }

        protected void dlRoles_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                CmsClass clazz = (CmsClass)e.Item.DataItem;
                IList<IRole> list = RoleController.GetRoleList(clazz.ID);
                Repeater rptRole = (Repeater)e.Item.FindControl("rptRole");
                rptRole.DataSource = list;
                rptRole.DataBind();
            }
        }

        public bool IsRole(long ID)
        {
            string RoleID = ID.ToString();
            if (ViewState["Roles"] != null)
            {
                string[] sRole = (string[])ViewState["Roles"];
                for (int i = 0; i < sRole.Length; i++)
                    if (sRole[i] == RoleID) return true;
            }
            return false;
        }

        public void DoHidden(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        public void DoShow(object sender, EventArgs e)
        {
            this.Visible = true;
        }

        public bool IsExist(string name)
        {
            IList<IUser> listUser = UserController.GetUserList(Convert.ToInt64(ddlClassPage.SelectedValue));

            foreach (IUser us in listUser)
            {
                if (name == us.Name) return false;
            }

            return true;
        }

        protected void ddlClassPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session[SessionVariable.Clazz.CurrentID] = ddlClassPage.SelectedValue;
            ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClassPage.SelectedValue));
            ucCmsExtPropertiesForm.PropertyList = clazz.PropertyList;
            if (ucCmsExtPropertiesForm.PropertyList.Count > 13) fsExt.Visible = true;            
            else fsExt.Visible = false;            
        }

    }
}
